/*
 * Copyright 2011 myTDev.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.mytdev.application.service.config;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.ResourceBundle.Control;

import com.mytdev.application.service.AbstractServiceProvider;

public class ResourcePropertiesConfigProvider extends AbstractServiceProvider<Config> implements ConfigProvider {

    public static final String FILE_PROPERTY = "file";

    @Override
    public Config getService() {
        String file = getFile();
        if (file.toLowerCase().endsWith(".properties")) {
            file = file.substring(0, file.length() - 11);
        }
        ResourceBundle resources = ResourceBundle.getBundle(
                file, Locale.ROOT,
                ConfigFileClassLoader.INSTANCE,
                Control.getControl(Control.FORMAT_PROPERTIES));
        return new ResourcePropertiesConfig(resources);
    }

    public String getFile() {
        return (String) getProperty(FILE_PROPERTY);
    }

    public void setFile(String file) {
        setProperty(FILE_PROPERTY, file);
    }

    private static class ConfigFileClassLoader extends ClassLoader {

        private static final ClassLoader INSTANCE = new ConfigFileClassLoader();

        @Override
        public URL getResource(String name) {
            URL url = super.getResource(name);
            if (url == null) {
                File file = new File(name);
                if (file.isFile()) {
                    try {
                        url = file.toURI().toURL();
                    } catch (MalformedURLException ex) {
                        throw new IllegalArgumentException(ex);
                    }
                }
            }
            if(url == null) {
                throw new IllegalArgumentException("config file not found");
            }
            return url;
        }
    }
}
